<template>
  <el-card class="box-card">
    <div slot="header" style="overflow: hidden;">
      <el-button type="primary" icon="el-icon-plus" style="float:right;" @click="isEditingSection = true">添加阶段
      </el-button>
    </div>
    <el-tree
      :data="sectionAndLessons"
      :props="defaultProps"
      draggable
      :allow-drop="handleAllowDrop"
      @node-drop="handleNodeDrop"
      :v-loading="isLoading"
    >
      <div class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span v-if="!data.sectionId">
          <el-button
            size="small"
            @click.stop="isEditingSection=true;sectionId=data.id;"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="primary"
            @click.stop="isEditingLesson=true;sectionId=data.id;sectionName=data.sectionName;"
          >
            添加课时
          </el-button>
          <el-button
            size="small"
            @click.stop="isEditingStatus=true;editItem=data;sectionId=data.id;"
          >
            {{data.status | processStatus}}
          </el-button>
        </span>
        <span v-else>
          <el-button
            size="small"
            @click="isEditingLesson=true;sectionId=data.sectionId;sectionName=sectionIdSectionNameMap[data.sectionId];lessonId=data.id;"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="success"
            @click="$router.push({name: 'course-video', params: {courseId, lessonId: data.id}})"
          >
            上传视频
          </el-button>
          <el-button
            size="small"
            @click="isEditingStatus=true;editItem=data;lessonId=data.id;"
          >
            {{data.status | processStatus}}
          </el-button>
        </span>
      </div>
    </el-tree>
    <create-or-edit-section
      v-if="isEditingSection"
      :course-id="courseId"
      :course-name="courseName"
      :section-id="sectionId"
      @close="isEditingSection=false;sectionId=undefined;"
      @success="isEditingSection=false;sectionId=undefined;loadSectionAndLesson();"
    ></create-or-edit-section>

    <create-or-edit-lesson
      v-if="isEditingLesson"
      :course-id="courseId"
      :course-name="courseName"
      :section-id="sectionId"
      :section-name="sectionName"
      :lesson-id="lessonId"
      @close="isEditingLesson=false;sectionId=undefined;sectionName=undefined;lessonId=undefined;"
      @success="isEditingLesson=false;sectionId=undefined;sectionName=undefined;lessonId=undefined;loadSectionAndLesson();"
    ></create-or-edit-lesson>

    <update-section-and-lesson-status
      v-if="isEditingStatus"
      :section-id="sectionId"
      :lesson-id="lessonId"
      v-model="editItem.status"
      @close="isEditingStatus=false;sectionId=undefined;lessonId=undefined;"
      @success="afterUpdateStatus"
    ></update-section-and-lesson-status>
  </el-card>
</template>

<script>
  import { getCourseById, getSectionAndLesson, saveOrUpdateSection, saveOrUpdateLesson } from '@/services/course'
  import CreateOrEditSection from './components/CreateOrEditSection'
  import CreateOrEditLesson from './components/CreateOrEditLesson'
  import UpdateSectionAndLessonStatus from './components/UpdateSectionAndLessonStatus'

  export default {
    name: 'CourseSection',
    props: {
      courseId: {
        type: [Number, String],
        required: true,
      }
    },
    data() {
      return {
        courseName: '',
        sectionAndLessons: [],
        defaultProps: {
          children: 'lessonDTOS',
          label: data => {
            return data.sectionName || data.theme
          }
        },
        isLoading: false,
        isEditingSection: false,
        sectionId: undefined,
        isEditingLesson: false,
        lessonId: undefined,
        sectionName: undefined,
        isEditingStatus: false,
        editItem: {},
      }
    },
    computed: {
      // sectionId -> sectionName
      sectionIdSectionNameMap() {
        const res = {}
        this.sectionAndLessons.forEach(section => {
          Object.assign(res, {
            [section.id]: section.sectionName
          })
        })
        console.log(res)
        return res
      }
    },
    created() {
      this.loadCourseData()
      this.loadSectionAndLesson()
    },
    methods: {
      async loadCourseData() {
        const { code, data } = await getCourseById(this.courseId)
        if (code === '000000') {
          this.courseName = data.courseName
        }
      },
      async loadSectionAndLesson() {
        const { code, data } = await getSectionAndLesson(this.courseId)
        if (code === '000000') {
          this.sectionAndLessons = data
        }
      },
      // 判断是否允许拖拽
      handleAllowDrop(draggingNode, dropNode, type) {
        // 1. 不能有放入内部的操作，例如不能把某个章节放入到另一个章节内部
        // 2. 不能有跨章节的拖拽，不允许把章节A的课时拖拽到章节B
        return type !== 'inner' && draggingNode.data.sectionId === dropNode.data.sectionId
      },
      // 拖拽完成后的回调
      async handleNodeDrop(draggingNode, dropNode, type, event) {
        console.log(draggingNode, dropNode, type, event)
        this.isLoading = true
        try {
          await Promise.all(dropNode.parent.childNodes.map((node, index) => {
            if (node.data.sectionId) {
              // 课时
              return saveOrUpdateLesson({
                id: node.data.id,
                orderNum: index,
              })
            } else {
              // 课程
              return saveOrUpdateSection({
                id: node.data.id,
                orderNum: index,
              })
            }
          }))
          this.$message.success('更新成功')
        } catch (error) {
          this.$message.error('更新失败')
          console.log(error)
        }
        this.isLoading = false
      },
      afterUpdateStatus(status) {
        this.isEditingStatus = false
        this.sectionId = undefined
        this.lessonId = undefined
        this.editItem.status = status
      }
    },
    filters: {
      processStatus(status) {
        let res
        switch (status) {
          case 0:
            res = '已隐藏'
            break
          case 1:
            res = '待更新'
            break
          case 2:
            res = '已更新'
            break
        }
        return res
      }
    },
    components: {
      CreateOrEditSection,
      CreateOrEditLesson,
      UpdateSectionAndLessonStatus,
    }
  }
</script>

<style lang="scss" scoped>
  ::v-deep .custom-tree-node {
    height: 50px;
    flex: 1; // 父元素是flex布局，指定为1可以占满一行
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-right: 10px;
  }

  ::v-deep .el-tree-node__content {
    height: auto;
  }
</style>
